package db;

import beans.B_Cliente;
import beans.B_Idioma;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import beans.B_PlanAuditoria;
import conexion.Conexion;
import java.sql.Types;

/**
 *
 * @author JoseHernan
 */
public class DB_PlanAuditoria {

    public static ArrayList<B_PlanAuditoria> getPlanAuditoriaActive() {
        ArrayList<B_PlanAuditoria> list = new ArrayList<B_PlanAuditoria>();
        try {
            Connection con = Conexion.getConexion();

            PreparedStatement ps;
            ResultSet rs;
            ps = con.prepareStatement(" select pa.id, pa.created_date, pa.id_idioma, pa.id_cliente, i.descripcion as idioma from tbl_plan_auditoria pa inner join tbl_idioma i on i.id = pa.id_idioma where pa.removed = false and pa.is_active = true ");
            rs = ps.executeQuery();
            B_PlanAuditoria obj;
            B_Idioma objIdioma;
            B_Cliente objCliente;
            while (rs.next()) {
                obj = new B_PlanAuditoria();
                //Asign values
                obj.setId(rs.getInt("id"));
                obj.setCreatedDate(rs.getString("created_date"));
                objIdioma = new B_Idioma();
                objIdioma.setId(rs.getInt("id_idioma"));
                objIdioma.setDescripcion(rs.getString("idioma"));
                obj.setObjIdioma(objIdioma);
                objCliente = new B_Cliente();
                objCliente.setId(rs.getInt("id_cliente"));
                obj.setObjCliente(objCliente);
                //Add to List
                list.add(obj);
            }
            rs.close();
            ps.close();
            con.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return list;
    }

    //SP CRUD
    public static String crud(B_PlanAuditoria obj, String action) {
        String result = "";
        CallableStatement cs = null;
        Connection con = Conexion.getConexion();
        try {
            cs = con.prepareCall("{call sp_crud_plan_auditoria(?,?,?,?,?,?,?)}");

            cs.registerOutParameter("p_message", Types.VARCHAR);
            cs.setString("p_action", action);
            cs.setInt("p_id", obj.getId());
            cs.setInt("p_id_idioma", obj.getObjIdioma().getId());
            cs.setInt("p_id_cliente", obj.getObjCliente().getId());
            cs.setBoolean("p_is_active", obj.isIsActive());
            cs.setString("p_user", obj.getUser());
            cs.executeUpdate();
            result = cs.getString(1);
        } catch (Exception ex) {
            result = ex.getMessage();
        } finally {
            try {
                cs.close();
                con.close();
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
        return result;
    }
}
